using System;
using System.IO;
using System.Xml;

namespace CosyTrade.Core
{
    public abstract class AddinBase : RemotingObject, IAddin, IDisposable
    {
        private string addinName = string.Empty;
        private IAddinManager currentAddinManager;

        public string AddinName
        {
            get
            {
                if(string.IsNullOrEmpty(addinName))
                {
                    Type currType = GetType();
                    AddinAttribute[] tags = (AddinAttribute[]) currType.GetCustomAttributes(typeof (AddinAttribute), false);
                    if (tags == null || tags.Length != 1) throw new RemotingException("Addin No Set AddinAttribute");
                    addinName = tags[0].AddinName;
                }
                return addinName;
            }
        }

        public void Initialize(IAddinManager addinManager)
        {
            currentAddinManager = addinManager;
            OnInitialize();
        }

        public void SystemInitalizeFinish()
        {
            OnSystemInitalizeFinish();
        }

        protected virtual void OnSystemInitalizeFinish(){}

        protected virtual void OnInitialize()
        {
        }

        public virtual void Terminate()
        {
        }
        
        public IAddinManager CurrentAddinManager
        {
            get { return currentAddinManager; }
        }

        protected XmlNode ConfigNode
        {
            get
            {
                XmlDocument cosyDoc = new XmlDocument();
                cosyDoc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CosyTrade.xml"));
                XmlNode currNode = cosyDoc.SelectSingleNode(string.Format(@"CosyTrade/Addin/{0}", AddinName));
                return currNode;
            }
        }

        public void Dispose()
        {
            AddinOnDispose();
        }

        protected virtual void AddinOnDispose()
        {
        }
    }
}